package org.fire.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 协议解码器
 * 
 * @author lhl
 *
 */
public class DefaultProtocolDecoder extends ByteToMessageDecoder
{
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception
	{
		if (in.readableBytes() < Packet.HEAD_SIZE)
		{
			return;
		}
		short dataLength = in.getShort(in.readerIndex());
		if (in.readableBytes() < dataLength || dataLength < Packet.HEAD_SIZE)
		{
			return;
		}
		dataLength = in.readShort();
		Packet packet = new Packet();
		short bodyLength = (short) (dataLength - Packet.HEAD_SIZE);
		if (bodyLength > 0)
		{
			byte[] body = new byte[bodyLength];
			packet.setBody(body);
			in.readBytes(body, 0, bodyLength);
		}
		System.out.println("[Recv] from " + ctx.channel().remoteAddress());

		out.add(packet);
	}
}
